package com.wangsd.web.face.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.enums.ResultCode;
import com.wangsd.web.MyController;
import com.wangsd.web.face.entity.*;
import com.wangsd.web.face.service.*;
import com.wangsd.web.sys.entity.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.List;

import static com.wangsd.common.enums.ResultCode.PRARM_NOT_NULL;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author generator
 * @since 2019-10-15
 */
@Api(value = "advertisement", tags = "广告位管理")
@RestController
@RequestMapping("/face/advertisement")
public class AdvertisementController extends MyController {
    @Autowired
    AdvertisementService advertisementService;

    @Autowired
    AdvertisementStoreRelationService advertisementStoreRelationService;

    @Autowired
    ServiceBusinessService businessService;

    @Autowired
    MerchantService merchantService;

    @Autowired
    StoreService storeService;

    @ApiOperation(value = "查询广告位列表", notes = "查询广告位列表", httpMethod = "POST")
    @PostMapping("/selectList/{pageNum}/{pageSize}")
    public Result selectList(@ApiParam(value = "当前页", required = true) @PathVariable Integer pageNum,
                             @ApiParam(value = "每页大小", required = true) @PathVariable Integer pageSize,
                             @RequestBody @ApiParam(name = "company", value = "传入json格式") Advertisement advertisement) {
        SysUser userInfo = getUserInfo();
        IPage<Advertisement> advertisementIPage = advertisementService.selectPage(userInfo.getCode(), pageNum, pageSize, advertisement);
        return Result.success(advertisementIPage);

    }

    @ApiOperation(value = "删除广告位", notes = "删除广告位", httpMethod = "GET", response = Result.class)
    @GetMapping("/delete/{id}")
    public Result delete(@ApiParam(value = "广告id", required = true) @PathVariable Long id) {
        boolean b = advertisementService.removeById(id);
        advertisementStoreRelationService.remove(new QueryWrapper<AdvertisementStoreRelation>()
                .eq("advertisement_id", id));
        return Result.success(b);
    }

    @ApiOperation(value = "通过区域查询门店信息List", notes = "通过区域查询门店信息List", httpMethod = "GET", response = Result.class)
    @GetMapping("/selectStoreByArea/{area}")
    public Result selectStoreByArea(@ApiParam(value = "区域id", required = true) @PathVariable String area) {
        SysUser userInfo = getUserInfo();
        String code = null;
        if (userInfo.getType() != 99) {
            code = userInfo.getCode();
        }
        JSONArray jsonArray = storeService.selectStoreByArea(area, code);
        return Result.success(jsonArray);
    }

    @ApiOperation(value = "新增或修改广告位", notes = "新增或修改广告位", httpMethod = "POST", response = Result.class)
    @PostMapping("/addOrUpdate")
    public Result addOrUpdate(@RequestBody Advertisement advertisement) {
        if (advertisement.getType() == 0) {
            if (advertisement.getBusinessId() == null) {
                return new Result(PRARM_NOT_NULL.getCode(), "服务商必填");
            } else {
                Advertisement query = new Advertisement();
                query.setBusinessId(advertisement.getBusinessId());
                Integer count = advertisementService.selectRightCount(query);
                if (count >= 5  && advertisement.getState() == 1) {
                    return new Result(PRARM_NOT_NULL.getCode(), "默认广告位最多只能有5个");
                }
                /*code 保存服务商code*/
                ServiceBusiness byId = businessService.getById(advertisement.getBusinessId());
                advertisement.setCode(byId.getCode());
            }
        } else if (advertisement.getType() == 1) {
            if (advertisement.getMerchantId() == null) {
                /*验证商户广告位不能超过5个*/
                Advertisement query = new Advertisement();
                query.setMerchantId(advertisement.getMerchantId());
                Integer count = advertisementService.selectRightCount(query);
                if (count >= 5 && advertisement.getState() == 1) {
                    return new Result(PRARM_NOT_NULL.getCode(), "商户广告位只能有5个");
                }
                return new Result(PRARM_NOT_NULL.getCode(), "商户必填");
            } else {
                /*code 保存商户code*/
                Merchant byId = merchantService.getById(advertisement.getMerchantId());
                advertisement.setCode(byId.getCode());
            }
        }

        /*判断当前门店下是否有超过5个广告，超过五个不允许添加*/
        /*if (advertisement.getStoreIdList() != null && advertisement.getStoreIdList().size() >0) {
            List<AdvertisementStoreRelation> relations = advertisementService.selectAdvertisementStoreCount(advertisement.getStoreIdList());
            for (AdvertisementStoreRelation relation:relations) {
                Integer count = relation.getCount();
                if (count >= 5) {
                    Store byId = storeService.getById(relation.getStoreId());
                    return new Result(PRARM_NOT_NULL.getCode(), byId.getName() + "只能有5个广告");
                }
            }
        }*/

        if (advertisement.getState() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "广告默认类型必填");
        }
        if (advertisement.getSourceType() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "广告类型必填");
        }
        if (advertisement.getSourceUrl() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "广告地址");
        }
        if (advertisement.getTransUrl() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "广告跳转地址");
        }
        if (advertisement.getDisplayTime() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "广告展示时间");
        }
        if (advertisement.getSort() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "广告展示排序");
        }

        advertisementService.addOrUpdate(advertisement);
        return Result.success();

    }

    @ApiOperation(value = "修改状态", notes = "修改状态", httpMethod = "POST", response = Result.class)
    @PostMapping("/updateStatus")
    public Result updateStatus(@RequestBody Advertisement advertisement) {

        if (advertisement.getId() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "id不能为空");
        }
        if (advertisement.getStatus() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "状态不能为空");
        }
        advertisementService.updateById(advertisement);
        return Result.success();

    }

    @ApiOperation(value = "通过广告id查询已选中门店", notes = "通过广告id查询已选中门店", httpMethod = "GET", response = Result.class)
    @GetMapping("/selectStoreIdsByAdvertisementId/{advertisementId}")
    public Result selectStoreIdsByAdvertisementId(@ApiParam(value = "广告id", required = true) @PathVariable Long advertisementId) {
        List<Long> ids = advertisementStoreRelationService.selectStoreIdsByAdvertisementId(advertisementId);
        return Result.success(ids);
    }

    @ApiOperation(value = "查询所有广告（注：非默认广告）", notes = "查询所有广告（注：非默认广告）", httpMethod = "GET", response = Result.class)
    @GetMapping("/selectAdvertisementAll")
    public Result selectAdvertisementAll() {
        SysUser userInfo = getUserInfo();
        String code = null;
        if (userInfo.getType() != 99) {
            code = userInfo.getCode();
        } else {
            return Result.fail("超级管理员不能分配广告！");
        }
        List<Advertisement> list = advertisementService.selectAdvertisementAll(code);
        return Result.success(list);
    }

    @ApiOperation(value = "已经选中的广告", notes = "已经选中的广告", httpMethod = "GET", response = Result.class)
    @GetMapping("/selectAdvertisementChoose")
    public Result selectAdvertisementChoose(@ApiParam(value = "门店id", required = true) Long storeId) {
        List<Long> longList = advertisementStoreRelationService.selectAdvertisementChoose(storeId);
        return Result.success(longList);
    }
}

